package ut.servlet.member.paypal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class SetPayment extends HttpServlet{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		int money;
		if(request.getParameter("money") == null){
			return;
		}else{
			try{
				money = Integer.parseInt(request.getParameter("money"));
				if(money < 200 || money > 50000){
					response.sendRedirect("/account/paypal.jsp?error=number");
					return;
				}
			}catch(NumberFormatException e){
				response.sendRedirect("/account/paypal.jsp?error=format");
				return;
			}
		}
		// 確認使用者已經完成信箱驗證
		ut.data.User user = (ut.data.User)request.getSession().getAttribute("user");
		if(user.verify == 0){
			return;
		}
		// 開始進行處理
		String body = ut.util.HttpClient.sendHttpRequest(System.getProperty("paypal.endpoint"),
			System.getProperty("paypal.auth") + "&METHOD=SetExpressCheckout&RETURNURL=" +
			java.net.URLEncoder.encode("http://ut.pada-x.com/account/paypal.jsp?money=" + money, "utf-8") +
			"&CANCELURL=http://ut.pada-x.com/account/paypal.jsp&PAYMENTACTION=Sale&PAYMENTREQUEST_0_CURRENCYCODE=TWD&PAYMENTREQUEST_0_AMT=" + money +
			"&PAYMENTREQUEST_0_ITEMAMT=" + money + "&PAYMENTREQUEST_0_PAYMENTACTION=Sale" +
			"&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital&L_PAYMENTREQUEST_0_NAME0=NTD" + money + "&L_PAYMENTREQUEST_0_QTY0=1&L_PAYMENTREQUEST_0_AMT0=" + money +
			"&REQCONFIRMSHIPPING=0&NOSHIPPING=1&LOCALECODE=zh_TW", false);
		if(body.indexOf("ACK=Success") > -1 || body.indexOf("ACK=SuccessWithWarning") > -1){
			int startIndex = body.indexOf("TOKEN=") + 6;
			int endIndex = body.indexOf("&", startIndex) > -1 ? body.indexOf("&", startIndex) : body.length();
			response.sendRedirect("https://www.paypal.com/incontext?token=" + java.net.URLDecoder.decode(body.substring(startIndex, endIndex), "utf-8"));
		}else{
			return;
		}
	}
}